package com.example.careycai.notepad;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
    private SearchView srv1;
    private Button addinfo,searchbtn;
    private List<Information_entity>information_entityList=new ArrayList<Information_entity>();
    private MyDatabaseHelper dbHelper;
    final String[] sr = {""};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        srv1=(SearchView)findViewById(R.id.srv1);
        dbHelper=new MyDatabaseHelper(this,"Notepad.db",null,1);
        dbHelper.getWritableDatabase();
        searchMethod();
        displayMethod();
        Button searchbtn=(Button)findViewById(R.id.button4);
        searchbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(sr[0]==null){
                    displayMethod();
                }else{
                    displayMethod1();
                }
            }
        });

    }
    private void displayMethod1() {
        final Information_entityAdapter adapter=new Information_entityAdapter(MainActivity.this,R.layout.mulu_item,information_entityList);
        final ListView listView=(ListView)findViewById(R.id.listView);
        listView.setAdapter(adapter);
        adapter.clear();
        SQLiteDatabase db=dbHelper.getWritableDatabase();
        //搜索信息
        String sql1 = "select id,title,place,content,time from information  where title LIKE '%" + sr[0] + "%'";
        Cursor cursor = db.rawQuery(sql1, null);
        if (cursor.moveToNext()){
            do{
                int id=cursor.getInt(cursor.getColumnIndex("id"));
                String title=cursor.getString(cursor.getColumnIndex("title"));
                String time=cursor.getString(cursor.getColumnIndex("time"));
                Log.d("MainActivity", "信息为：" + id + title + time);
                Information_entity title1=new Information_entity(id,title,"place","content",time);
                information_entityList.add(title1);
            }while (cursor.moveToNext());
        }
        cursor.close();

        //新建记事本功能模块
        addinfo=(Button)findViewById(R.id.creat);
        addinfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, Addinfo.class);
                startActivity(intent);
            }
        });

        //点击listview子项进入信息页面

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Information_entity in = information_entityList.get(position);
                Intent intent = new Intent(MainActivity.this, Inforactivity.class);
                intent.putExtra("time", in.getTime());
                Toast.makeText(MainActivity.this, in.getTime(), Toast.LENGTH_SHORT).show();
                startActivity(intent);

            }
        });

        //listView长按事件
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()

        {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                                           final int position, final long id) {
                final String data = Integer.toString(position + 1);

                final Information_entity information_entity = information_entityList.get(position);
                //Toast.makeText(MainActivity.this,id+"数据库id:"+information_entity.getId()+information_entity.getTitle(),Toast.LENGTH_SHORT).show();
                Dialog dialog = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("删除信息")
                        .setMessage("您确定要删除"+information_entity.getTitle()+"吗？")
                        .setIcon(R.mipmap.ic_launcher)
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int which) {
                                        //根据标题或时间，从数据库中实现删除信息功能
                                        SQLiteDatabase db = dbHelper.getWritableDatabase();
                                        db.execSQL("delete from information where id=" +information_entity.getId());
                                        Toast.makeText(MainActivity.this, "删除"+information_entity.getTitle()+"成功", Toast.LENGTH_LONG).show();

                                       // Information_entityAdapter adapter=new Information_entityAdapter(MainActivity.this,R.layout.mulu_item,information_entityList);
                                        ListView listView=(ListView)findViewById(R.id.listView);
                                        //adapter.notifyDataSetChanged();
                                        //listView.getAdapter();
                                        //listView.setAdapter(adapter);

                                        //Intent intent=new Intent(MainActivity.this,MainActivity.class);
                                        //startActivity(intent);
                                       // finish(); //为了演示效果，不进行真实退出，用土司代替
                                    }
                                })

                        .setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface arg0, int arg1) {
                                        Intent intent = new Intent(MainActivity.this, MainActivity.class);
                                        startActivity(intent);
                                    }
                                }).create();
                dialog.show();
                return true;
            }
        });


    }
    private void displayMethod() {
        final Information_entityAdapter adapter=new Information_entityAdapter(MainActivity.this,R.layout.mulu_item,information_entityList);
        final ListView listView=(ListView)findViewById(R.id.listView);
        listView.setAdapter(adapter);
        adapter.clear();
        SQLiteDatabase db=dbHelper.getWritableDatabase();
            //查询信息
            Cursor cursor=db.query("information",null,null,null,null,null,null);
        if (cursor.moveToNext()){
                do{
                    int id=cursor.getInt(cursor.getColumnIndex("id"));
                    String title=cursor.getString(cursor.getColumnIndex("title"));
                    String time=cursor.getString(cursor.getColumnIndex("time"));

                    SimpleDateFormat originalTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = null;
                    try {
                        date = originalTime.parse(time);
                        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
                        time = format.format(date);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    Log.d("MainActivity", "信息为：" + id + title + time);
                    Information_entity title1=new Information_entity(id,title,"place","content",time);
                    information_entityList.add(title1);
                }while (cursor.moveToNext());
            }
            cursor.close();

        //新建记事本功能模块
        addinfo=(Button)findViewById(R.id.creat);
        addinfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, Addinfo.class);
                startActivity(intent);
            }
        });

        //点击listview子项进入信息页面

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Information_entity in = information_entityList.get(position);
                Intent intent = new Intent(MainActivity.this, Inforactivity.class);
                intent.putExtra("time", in.getTime());
                Toast.makeText(MainActivity.this, in.getTime(), Toast.LENGTH_SHORT).show();
                startActivity(intent);

            }
        });

        //listView长按事件
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()

        {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                                           final int position, long id) {
                final String data = Integer.toString(position + 1);

                final Information_entity information_entity = information_entityList.get(position);
                //Toast.makeText(MainActivity.this,id+"数据库id:"+information_entity.getId()+information_entity.getTitle(),Toast.LENGTH_SHORT).show();
                Dialog dialog = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("删除信息")
                        .setMessage("您确定要删除"+information_entity.getTitle()+"吗？")
                        .setIcon(R.mipmap.ic_launcher)
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int which) {
                                        //根据标题或时间，从数据库中实现删除信息功能
                                        SQLiteDatabase db = dbHelper.getWritableDatabase();
                                        db.execSQL("delete from information where id=" +information_entity.getId());
                                        Toast.makeText(MainActivity.this, "删除"+information_entity.getTitle()+"成功", Toast.LENGTH_LONG).show();

                                        Information_entityAdapter adapter=new Information_entityAdapter(MainActivity.this,R.layout.mulu_item,information_entityList);
                                        ListView listView=(ListView)findViewById(R.id.listView);
                                        adapter.notifyDataSetChanged();
                                        listView.getAdapter();
                                        listView.setAdapter(adapter);

                                        Intent intent=new Intent(MainActivity.this,MainActivity.class);
                                        startActivity(intent);
                                        finish(); //为了演示效果，不进行真实退出，用土司代替
                                    }
                                })

                        .setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface arg0, int arg1) {
                                        Intent intent = new Intent(MainActivity.this, MainActivity.class);
                                        startActivity(intent);
                                    }
                                }).create();
                dialog.show();
                return true;
            }
        });


    }

    private void searchMethod() {

        //搜索点击事件
        final SearchView srv1=(SearchView)findViewById(R.id.srv1);



        srv1.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {

                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                sr[0] = newText;
                if(sr[0]==null){
                    displayMethod();
                }else{
                    displayMethod1();}
                return false;
            }
        });


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_mulu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }



}

